package com.ttbj.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.ttbj.util.ResultUtil;
import com.ttbj.util.SafetyUtils;

public abstract class DefultCheckInterceptorApater extends HandlerInterceptorAdapter {
	
	public static final Logger logger = LoggerFactory.getLogger(DefultCheckInterceptorApater.class);

	abstract  Object getUser(String token) throws Exception;
	
	private List<String> excludePaths = null;
	private String excludePath; // 匹配不拦截请求url

	public String getExcludePath() {
		return excludePath;
	}

	public void setExcludePath(String excludePath) {
		this.excludePath = excludePath;
	}

	@Override
	@SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String path = request.getServletPath();// 用户请求的url
		logger.info("验证token拦截器");
		excludePaths = new ArrayList<String>();
		if (StringUtils.isNotEmpty(excludePath)) {
			String[] paths = excludePath.split(";");
			for (String p : paths) {
				if (!StringUtils.isEmpty(p)) {
					excludePaths.add(p.trim());
				}
			}
		}
		PathMatcher matcher = new AntPathMatcher();
		for (String str : excludePaths) {
			if (matcher.match(str, path)) {
				return super.preHandle(request, response, handler);
			}
		}
		/* 用户验证信息 */
		Map<String, String[]> map = request.getParameterMap();
		// 测试或空参函数通过excludePath配置
		if (null == map || map.isEmpty() || !map.containsKey("token")) {
			SafetyUtils.error(response, ResultUtil.createFail("messages", 115, null), "token不存在");
			return false;
		}
		String token = map.get("token")[0];
		logger.info("拦截到的token为:{}",token);
		if (isEmpty(token)) {
			SafetyUtils.error(response, ResultUtil.createFail("messages", 115, null), "token为空");
			return false;
		}
		Object user = getUser (token);
		if (null == user) {
			SafetyUtils.error(response, ResultUtil.createFail("messages", 115, null), "token未查询到用户信息");
			return false;
		}
		/* 如果不为null,给request加入 */
		request.setAttribute("user", user);
		return super.preHandle(request, response, handler);
	}

	private boolean isEmpty(String s) {
		if (null == s || s.isEmpty()) {
			return true;
		}
		return false;
	}
}
